from django.shortcuts import render, HttpResponse, redirect
from utils.sms.send import send_sms_single
import random
from django.conf import settings


# 15670883607

def send_sms(request):
    '''发送短信
    ？tpl=login
    ?tpl = register
    '''

    tpl = request.GET.get('tpl')
    tpl_id = settings.PYTHON_SMS_TEMPLATE.get(tpl)
    if not tpl_id:
        return HttpResponse('模板不存在')

    code = random.randrange(1000, 9999)
    ret = send_sms_single('19803630852', tpl_id, [code])
    if ret['result'] == 0:
        return HttpResponse('成功')
    return HttpResponse(ret['errmsg'])


# ModelForm 验证
from app01 import models
from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError


class RegisterModelForm(forms.ModelForm):
    telephone = forms.CharField(label='手机号码', validators=[RegexValidator(r'^1[3-9][0-9]{9}$', '手机号格式错误'), ], )
    code = forms.CharField(label='验证码',
                           widget=forms.TextInput(
                               attrs={'placeholder': '请输入验证码'}))

    re_password = forms.CharField(label='确认密码',
                                  widget=forms.PasswordInput(
                                      attrs={'placeholder': '请输入密码'}))

    password = forms.CharField(label='密码',
                               widget=forms.PasswordInput(
                                   attrs={'placeholder': '请再次输入密码'}))

    class Meta:
        model = models.UserIfo
        fields = ['username', 'password', 're_password', 'email', 'telephone', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            # field 出来的是一个对象
            # print(name, field)
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = f'请输入{field.label}'


# 注册界面
def Register(request):
    form = RegisterModelForm()
    return render(request, 'app01/templates/app01/register.html', locals())
